package com.qf.web;

import com.alibaba.fastjson.JSON;
import com.qf.common.R;
import com.qf.pojo.User;
import com.qf.service.UserService;
import com.qf.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @date 2022/4/1
 * @desc
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String username = req.getParameter("username");
        String password = req.getParameter("password");


        User user = new User();
        user.setUsername(username);
        user.setPassword(password);

        UserService userService = new UserServiceImpl();

        User currentUser = userService.login(user);

        R<User> r = new R();


        if(currentUser!=null){
            //登录成功
            r.setCode(200);
            r.setMsg("登录成功");
            r.setData(currentUser);
            String jsonResult = JSON.toJSONString(r);

            resp.getWriter().println(jsonResult);
        }else{
            //登录失败
            r.setCode(500);
            r.setMsg("用户名或密码错误");
            String jsonResult = JSON.toJSONString(r);
            resp.getWriter().println(jsonResult);
        }
    }
}
